﻿using CommonDevelop;
using CommonDevelop.DB;
using CommonEngine;
using CommonFP;
using ManageDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace ManageRepository
{
    /// <summary>
    /// 部门数据层接口
    /// </summary>
    public interface IDeptRepository : IBase<Base_Dept>
    {
        /// <summary>
        /// 通过机构ID取部门集合
        /// </summary>
        IEnumerable<Base_Dept> GetDeptsByCompanyId(string CompanyId);
    }

    /// <summary>
    /// 部门数据层
    /// </summary>
    public class DeptRepository : DBBase<Base_Dept>, IDeptRepository
    {
        public override Expression<Func<Base_Dept, bool>> WhereKeyWord(string keyword)
            => t => t.FullName.Contains(keyword) || t.DeptCode.Contains(keyword);

        /// <summary>
        /// 通过机构ID取部门集合
        /// </summary>
        public IEnumerable<Base_Dept> GetDeptsByCompanyId(string CompanyId)
            => CompanyId.IsEmpty() ? new List<Base_Dept>()
            : SugarBizDB.GetReadOnlyMore<Base_Dept>(a => a.CompanyId == CompanyId);

        /// <summary>
        /// 拉关系，部门主键=>部门信息、部门子集
        /// </summary>
        public override IEnumerable<TVO> GetPull<TVO>(Base_Dept en)
        {
            if (en == null || en.DeptId.IsEmpty())
                return base.GetPull<TVO>(en);

            if (typeof(TVO).Equals(typeof(Base_Dept)))
            {
                List<Base_Dept> result = new List<Base_Dept>();
                en.DeptId.ToOption()
                    .Map(a => this.GetList(d => d.ParentId == a))
                    .ForEach(a => result.AddRange(a));

                return result.Cast<TVO>().ToList();
            }
            else
                return base.GetPull<TVO>(en);
        }

        /// <summary>
        /// 推关系，部门信息、子部门=> 上级部门主键
        /// </summary>
        public override IEnumerable<Base_Dept> GetPush<TVO>(TVO en)
        {
            var result = base.GetPush<TVO>(en);
            if (en == null)
                return result;

            if (typeof(TVO).Equals(typeof(Base_Dept)))
            {
                (en as Base_Dept)
                    .ToOption()
                    .Map(a => this.GetEntity(a.ParentId))
                    .ForEach(a => result.Append(a));
                return result;
            }
            else if (typeof(TVO).Equals(typeof(Base_Company)))
            {
                (en as Base_Company)
                    .ToOption()
                    .Map(a => this.GetEntity(m => m.CompanyId == a.CompanyId, false))
                    .ForEach(a => result.Append(a));
                return result;
            }
            else
                return result;
        }
    }
}
